<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>部门测评打分 - IVT绩效考核系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background-color: #f5f5f5;
            color: #333;
            padding-bottom: 80px;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .back-btn {
            background: none;
            border: none;
            color: white;
            font-size: 18px;
            cursor: pointer;
            margin-right: 15px;
            padding: 5px;
        }

        .header h1 {
            font-size: 18px;
            font-weight: 600;
        }

        .eval-info {
            background: white;
            margin: 20px;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .dept-name {
            font-size: 20px;
            font-weight: 600;
            color: #1976d2;
            margin-bottom: 10px;
        }


        .evaluation-form {
            margin: 0 20px;
        }

        .question-item {
            background: white;
            margin-bottom: 20px;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .question-item:last-child {
            margin-bottom: 40px;
        }

        .question-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 10px;
            color: #333;
        }

        .question-desc {
            font-size: 14px;
            color: #666;
            line-height: 1.6;
            margin-bottom: 15px;
            white-space: pre-line;
        }

        .options {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 10px;
        }

        .option {
            text-align: center;
            padding: 8px 6px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .option.selected {
            background: #1976d2;
            color: white;
            border-color: #1976d2;
        }

        .option-label {
            font-weight: 600;
            font-size: 14px;
            margin-bottom: 2px;
        }

        .option-score {
            font-size: 11px;
            opacity: 0.8;
        }

        .submit-section {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            padding: 15px 20px;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
        }

        .total-score-bottom {
            text-align: center;
            margin-bottom: 15px;
            font-size: 16px;
            color: #333;
        }

        .total-value-bottom {
            font-size: 24px;
            font-weight: 600;
            color: #667eea;
        }

        .submit-btn {
            width: 100%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 8px;
            padding: 15px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
        }

        .submit-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .loading {
            text-align: center;
            padding: 50px;
            color: #666;
        }

        .error {
            background: #ffebee;
            color: #c62828;
            padding: 15px;
            margin: 20px;
            border-radius: 8px;
            text-align: center;
        }

        .success {
            background: #e8f5e8;
            color: #388e3c;
            padding: 15px;
            margin: 20px;
            border-radius: 8px;
            text-align: center;
        }


    </style>
</head>
<body>
<div class="header">
    <button class="back-btn" onclick="goBack()">‹</button>
    <h1 id="headerTitle">部门测评打分</h1>
</div>

<div class="loading" id="loading">
    正在加载测评内容...
</div>

<div class="error" id="error" style="display:none;"></div>

<div id="main-content" style="display:none;">
    <div class="eval-info">
        <div class="dept-name" id="deptName"></div>
    </div>

    <div class="evaluation-form" id="evaluationForm">
        <!-- 动态加载测评内容 -->
    </div>
</div>

<div class="submit-section" id="submitSection" style="display: none;">
    <div class="total-score-bottom">
        总分：<span class="total-value-bottom" id="totalScoreBottom">0</span>
    </div>
    <button class="submit-btn" disabled id="submitBtn" onclick="submitEvaluation()">
        提交测评
    </button>
</div>

<script>
        let relationId = null;
        let deptName = null;
        let totalScore = null;
        let evaluationData = {};
        let questions = [];

        // 获取URL参数
        function getQueryParam(name) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        }

        // 返回上一页
        function goBack() {
            history.back();
        }

        // 选择答案
        function selectOption(questionIndex, option, score, element) {
            // 确保score是有效的数字
            const validScore = parseInt(score) || 0;
            evaluationData[questionIndex] = { option, score: validScore };

            // 更新UI
            const options = document.querySelectorAll(`[data-question="${questionIndex}"] .option`);
            options.forEach(opt => opt.classList.remove('selected'));
            
            // 如果没有传递element参数，尝试从event获取
            const targetElement = element || event.target;
            if (targetElement) {
                targetElement.classList.add('selected');
            }

            // 更新总分
            updateTotalScore();
            
            // 检查是否所有题目都已回答
            checkFormComplete();
        }

        // 更新总分
        function updateTotalScore() {
            const total = Object.values(evaluationData).reduce((sum, item) => sum + parseInt(item.score), 0);
            document.getElementById('totalScoreBottom').textContent = total;
        }

        // 检查表单是否完整
        function checkFormComplete() {
            const submitBtn = document.getElementById('submitBtn');
            const isComplete = Object.keys(evaluationData).length === questions.length;
            submitBtn.disabled = !isComplete;
        }

        // 格式化考核点详解
        function formatDescription(desc) {
            return desc.replace(/。/g, '。\n').trim();
        }

        // 加载测评内容
        async function loadEvaluationContent() {
            try {
                const response = await fetch(`/evaluation/api/h5/dept/content?relationId=${relationId}`);
                const result = await response.json();

                if (result.success) {
                    questions = result.data;
                    renderEvaluationForm();
                } else {
                    showError(result.message || '加载测评内容失败');
                }
            } catch (error) {
                console.error('加载测评内容失败:', error);
                showError('网络错误，请稍后重试');
            }
        }

        // 渲染测评表单
        function renderEvaluationForm() {
            const loading = document.getElementById('loading');
            const mainContent = document.getElementById('main-content');
            const evaluationForm = document.getElementById('evaluationForm');

            loading.style.display = 'none';
            mainContent.style.display = 'block';

            // 设置部门信息
            const decodedDeptName = decodeURIComponent(deptName);
            document.getElementById('deptName').textContent = '部门名称：' + (decodedDeptName !== 'undefined' && decodedDeptName !== 'null' ? decodedDeptName : '未知部门');
            
            // 显示底部总分区域
            document.getElementById('submitSection').style.display = 'block';

            // 渲染题目
            const html = questions.map((question, index) => `
                <div class="question-item" data-question="${index}">
                    <div class="question-title">${question.khdmc || question.KHDMC || '未知指标'}</div>
                    <div class="question-desc">${formatDescription(question.khdxj || question.KHDXJ || '暂无详细说明')}</div>
                    <div class="options">
                        <div class="option" onclick="selectOption(${index}, 'A', ${question.a || question.A || 0}, this)">
                            <div class="option-label">A</div>
                            <div class="option-score">${question.a || question.A || 0}分</div>
                        </div>
                        <div class="option" onclick="selectOption(${index}, 'B', ${question.b || question.B || 0}, this)">
                            <div class="option-label">B</div>
                            <div class="option-score">${question.b || question.B || 0}分</div>
                        </div>
                        <div class="option" onclick="selectOption(${index}, 'C', ${question.c || question.C || 0}, this)">
                            <div class="option-label">C</div>
                            <div class="option-score">${question.c || question.C || 0}分</div>
                        </div>
                        <div class="option" onclick="selectOption(${index}, 'D', ${question.d || question.D || 0}, this)">
                            <div class="option-label">D</div>
                            <div class="option-score">${question.d || question.D || 0}分</div>
                        </div>
                        <div class="option" onclick="selectOption(${index}, 'E', ${question.e || question.E || 0}, this)">
                            <div class="option-label">E</div>
                            <div class="option-score">${question.e || question.E || 0}分</div>
                        </div>
                    </div>
                </div>
            `).join('');

            evaluationForm.innerHTML = html;
        }

        // 提交测评
        async function submitEvaluation() {
            const submitBtn = document.getElementById('submitBtn');
            submitBtn.disabled = true;
            submitBtn.textContent = '提交中...';

            try {
                // 构造提交数据
                const scores = questions.map((question, index) => {
                    const answer = evaluationData[index];
                    return {
                        khdbh: question.khdbh || question.KHDBH,
                        score: parseInt(answer.score) || 0
                    };
                });

                const response = await fetch('/evaluation/api/h5/dept/submit', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        relationId: parseInt(relationId) || 0,
                        scores: scores
                    })
                });

                const result = await response.json();

                if (result.success) {
                    showSuccess('测评提交成功！');
                    setTimeout(() => {
                        // 返回部门测评页面并刷新
                        window.location.href = 'dept-list.html';
                    }, 2000);
                } else {
                    showError(result.message || '提交失败');
                    submitBtn.disabled = false;
                    submitBtn.textContent = '提交测评';
                }
            } catch (error) {
                console.error('提交测评失败:', error);
                showError('网络错误，请稍后重试');
                submitBtn.disabled = false;
                submitBtn.textContent = '提交测评';
            }
        }

        function showError(message) {
            document.getElementById('loading').style.display = 'none';
            document.getElementById('error').style.display = 'block';
            document.getElementById('error').textContent = message;
        }

        function showSuccess(message) {
            const successDiv = document.createElement('div');
            successDiv.className = 'success';
            successDiv.textContent = message;
            document.body.insertBefore(successDiv, document.getElementById('main-content'));
        }

        // 页面加载时初始化
        window.onload = function() {
            relationId = getQueryParam('id');
            deptName = getQueryParam('deptName');
            totalScore = getQueryParam('totalScore');

            if (!relationId || relationId === 'undefined' || relationId === 'null') {
                showError('测评关系ID参数错误');
                return;
            }

            if (!deptName || deptName === 'undefined' || deptName === 'null') {
                deptName = '未知部门';
            }

            loadEvaluationContent();
        };


</script>
</body>
</html>
